package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.StageTimeoutRemindEntity;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.ProGetHelp;
import com.xbongbong.paas.help.StageDetailHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.StageTimeoutRemindModel;
import com.xbongbong.paas.pojo.StageMessageContentPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.message.SendMessageUtil;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.saas.service.ScheduleTaskActionService;
import com.xbongbong.schedule.domain.entity.ScheduleTaskEntity;
import com.xbongbong.schedule.domain.entity.ScheduleTaskRelateBusinessEntity;
import com.xbongbong.schedule.enums.ScheduleTaskTypeEnum;
import com.xbongbong.schedule.pojo.dto.ScheduleTaskActionDTO;
import com.xbongbong.schedule.pojo.vo.ScheduleTaskActionVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;


@Service("scheduleTaskActionService")
public class ScheduleTaskActionServiceImpl implements ScheduleTaskActionService {

    private static final Logger LOG = LoggerFactory.getLogger(ScheduleTaskActionServiceImpl.class);

    @Resource
    private MessageService messageService;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private StageTimeoutRemindModel stageTimeoutRemindModel;
    @Resource
    private ProGetHelp proGetHelp;
    @Resource
    private StageDetailHelp stageDetailHelp;
    @Resource
    private ProFormHelp proFormHelp;

    /**
     * 延时任务消费者具体执行的事件
     *
     * @param scheduleTaskActionDTO
     * @return ScheduleTaskActionVO
     */
    @Override
    public ScheduleTaskActionVO scheduleTaskAction(ScheduleTaskActionDTO scheduleTaskActionDTO) throws XbbException {
        ScheduleTaskEntity scheduleTaskEntity = scheduleTaskActionDTO.getScheduleTaskEntity();
        ScheduleTaskRelateBusinessEntity scheduleTaskRelateBusinessEntity = scheduleTaskActionDTO.getScheduleTaskRelateBusinessEntity();
        if (Objects.isNull(scheduleTaskEntity) || Objects.isNull(scheduleTaskRelateBusinessEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "scheduleTaskEntity或者scheduleTaskRelateBusinessEntity为空");
        }
        if (Objects.equals(scheduleTaskEntity.getScheduleType(), ScheduleTaskTypeEnum.STAGE_TIMEOUT_REMIND.getCode())) {
            stageTimeOutRemindPush(scheduleTaskRelateBusinessEntity);
        }
        return new ScheduleTaskActionVO();
    }

    @Override
    public void stageTimeOutRemindPush(ScheduleTaskRelateBusinessEntity scheduleTaskRelateBusinessEntity) throws XbbException {
        String corpid = scheduleTaskRelateBusinessEntity.getCorpid();
        Integer businessType = scheduleTaskRelateBusinessEntity.getBusinessType();
        Integer saasMark = scheduleTaskRelateBusinessEntity.getSaasMark();
        Long dataId = scheduleTaskRelateBusinessEntity.getDataId();
        Long formId = scheduleTaskRelateBusinessEntity.getFormId();
        Long setId = scheduleTaskRelateBusinessEntity.getSetId();

        StageTimeoutRemindEntity stageTimeoutRemindEntity = stageTimeoutRemindModel.getByKey(setId, corpid);
        JSONArray remindUserArray = Objects.isNull(stageTimeoutRemindEntity.getRemindUser()) ? new JSONArray() : stageTimeoutRemindEntity.getRemindUser();
        JSONArray remindContentArray = Objects.isNull(stageTimeoutRemindEntity.getRemindContent()) ? new JSONArray() : stageTimeoutRemindEntity.getRemindContent();
        //通知人
        List<OptionalRangeEntity> remindUserList = remindUserArray.toJavaList(OptionalRangeEntity.class);
        if (CollectionsUtil.isEmpty(remindUserList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "阶段发送超时消息节点,消息接收人为空");
        }
        //消息内容
        List<StageMessageContentPojo> remindContent = remindContentArray.toJavaList(StageMessageContentPojo.class);
        if (CollectionsUtil.isEmpty(remindContent)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "阶段发送超时消息节点,消息内容为空");
        }
        //获取表单解释
        PaasFormExplainEntity explain = proFormHelp.getExplainEntity(corpid, formId, businessType);
        Map<String, FieldAttrEntity> formExplainMap = ExplainUtil.getExplainMap(explain.getExplains());
        //获取提醒的表单字段
        PaasFormDataEntityExt paasFormDataEntityExt = proGetHelp.getByKey(dataId, businessType, saasMark, corpid);
        // 拼接消息内容
        String messageContent = stageDetailHelp.getContentValue(remindContent, formExplainMap, paasFormDataEntityExt);
        // 目前是默认标题
        String title = ScheduleTaskTypeEnum.STAGE_TIMEOUT_REMIND.getMemo();
        // 获取通知人
        Set<String> pushUserList = stageDetailHelp.getUserListByOptionalRange(corpid, saasMark, businessType, dataId, remindUserList);
        if (CollectionUtils.isEmpty(pushUserList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "阶段发送超时消息节点,通知人为空");
        }
        // 延缓十秒发送
        Long pushTime = DateTimeUtil.getInt() + 10;
        // 推送类型
        PushTypeEnum pushTypeEnum = PushTypeEnum.getStageTimeoutRemindPushType(businessType);
        // 详情页穿透查看信息
        PaasFormEntity paasFormEntity = paasFormModel.getByFormId(formId, corpid);
        PushRefTypePojo.Options options = SendMessageUtil.getDetailOptions(paasFormEntity.getAppId(), paasFormEntity.getMenuId(), formId, dataId, saasMark, businessType, businessType);
        if (Objects.equals(pushTypeEnum, PushTypeEnum.PAAS_STAGE_TIMEOUT_REMIND_PUSH)) {
            PaasMenuEntity paasMenuEntity = paasMenuModel.getByKey(paasFormEntity.getMenuId(), corpid);
            options.setName(paasMenuEntity.getName());
        }
        MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, new ArrayList<>(pushUserList), Collections.singletonList(dataId), 0, pushTime, title, messageContent, null, options);
        messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, pushTypeEnum);
    }
}
